package booksys.Mhome;


import booksys.common.CurrentUser;
import booksys.common.Result;
import booksys.common.Utils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.util.Map;
import java.util.UUID;

@MultipartConfig //此注解表示可以接收上传文件
@WebServlet({
        "/Mcurrent-user",//获取当前用户信息
        "/Mavatar",//获取头像
        "/Mexit",//退出系统
        "/MdoUpd",//修改用户信息
        "/MdoUpdPassword"//修改密码
})
public class HomeAPI extends HttpServlet {

    //该方法在Servlet初始化时执行，仅执行一次
    @Override
    public void init() throws ServletException {
        File dir = new File(CurrentUser.AVATAR_DIR);//表示文件或目录的路径
        if(!dir.exists()){//目录不存在则创建
            dir.mkdirs();

        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HomeService service = new HomeService();
        request.setCharacterEncoding("UTF-8");//设置请求编码，防止获取请求信息中文乱码
        String path = request.getServletPath();//获取请求路径
        CurrentUser currentUser = (CurrentUser)request.getSession().getAttribute(CurrentUser.SESSION_ATTR_NAME);
        if("/Mavatar".equals(path)){
            Part part = request.getPart("avatar");

            InputStream in = part.getInputStream();

            String name = UUID.randomUUID().toString();//获得通过uuid算法得到的不重复的字符串
            String submitedFilename = part.getSubmittedFileName();//原始文件名
            String suffix = submitedFilename.substring(submitedFilename.lastIndexOf("."));
            String filename = name+suffix;
            OutputStream out = new FileOutputStream(CurrentUser.AVATAR_DIR+"/"+filename);

            byte[] b = new byte[10240];//容量为10240字节的缓存区
            int len = -1;//从输入流读取并放入缓存区的数据量

            while((len=in.read(b))!=-1){
                out.write(b,0,len);
            }
            out.flush();
            out.close();
            in.close();

            service.setAvatar(currentUser,filename);

            Utils.outResult(response, Result.success());
        }
        if("/Mexit".equals(path)){
            request.getSession().removeAttribute(CurrentUser.SESSION_ATTR_NAME);
            Utils.outResult(response, Result.success());
        }
        if ("/MdoUpd".equals(path)) {
            try {
                Map<String,Object>dto = Utils.getBeanFromRequest(Map.class, request);
                service.updManager(dto);
                Utils.outJson(response, Result.success());
            } catch (Exception e) {
                e.printStackTrace();
                Utils.outJson(response, Result.fail(Result.ERR_CODE_BUSINESS, e.getMessage()));
            }
        }
        if ("/MdoUpdPassword".equals(path)) {
            try {
                Map<String,Object>dto = Utils.getBeanFromRequest(Map.class, request);
                service.updPassword(dto);
                Utils.outJson(response, Result.success());
            } catch (Exception e) {
                e.printStackTrace();
                Utils.outJson(response, Result.fail(Result.ERR_CODE_BUSINESS, e.getMessage()));
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = request.getServletPath();//获取请求路径

        HomeService service = new HomeService();

        if("/Mcurrent-user".equals(path)){

            CurrentUser currentUser = (CurrentUser)request.getSession().getAttribute(CurrentUser.SESSION_ATTR_NAME);
            System.out.println("currentUser->"+currentUser);
            service.loadCurrentUser(currentUser);//加载完整的用户信息

            Utils.outResult(response, Result.success(currentUser));

        }

        if("/Mavatar".equals(path)){
            //从请求参数中通过参数名称filename获取文件名称
            String filename = request.getParameter("filename");
            //读取文件的输入流
            InputStream in = new FileInputStream(CurrentUser.AVATAR_DIR+"/"+filename);
            //将文件信息输出到浏览器的输出流
            OutputStream out = response.getOutputStream();

            byte[] b = new byte[10240];//容量为10240字节的缓存区
            int len = -1;//从输入流读取并放入缓存区的数据量

            while((len=in.read(b))!=-1){
                out.write(b,0,len);
            }
            out.flush();
            out.close();
            in.close();

        }
    }
}
